package com.example.community.rest;

import com.example.community.dto.LoginUserDto;
import com.example.community.model.User;
import com.example.community.service.UserService;
import com.example.community.util.GetIpAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;

@RequestMapping("/authorize")
@RestController
public class LoginResource {
    @Autowired
    private UserService userService;

    @PostMapping("/passwordLogin")
    public void loginByPassword(@RequestBody LoginUserDto loginUserDto,
                                              HttpServletResponse response,
                                HttpServletRequest request) throws HttpRequestMethodNotSupportedException {
        User user = new User();
        String token = UUID.randomUUID().toString();
        user.setToken("UR"+token);
        user.setPhone(loginUserDto.getPhone());
        user.setPassword(loginUserDto.getPassword());
        String ip = GetIpAddress.getIp(request);
        userService.loginUser(user,ip);
        Cookie cookie = new Cookie("token", "UR" + token);
        cookie.setMaxAge(60 * 60 * 24 * 15);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
